package fy.erp.check;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import fy.form.listen.bean.UserBean;
import fy.form.listen.dao.MemberDao;
import fy.util.MyUtil;

public class AllowMemberManager {
	private static long[] members;

	private static boolean first = true;

	private static String[] memberCodeArray;

	public static long[] getAllowMembers(boolean reset) {
		if (first || reset) {
			first = false;
			members = null;
			try {
				BufferedReader reader = MyUtil.createBufferedReader(
						MyUtil.getRealPath(AllowMemberManager.class)
								+ "allowMember", "utf-8");
				String member = null;
				List<String> memberCodes = new ArrayList<String>();
				while ((member = reader.readLine()) != null) {
					if (!"".equals(member)) {
						memberCodes.add(member);
					}
				}

				String[] memberArray = memberCodes
						.toArray(new String[memberCodes.size()]);

				List<UserBean> userBeans = MemberDao
						.queryMemberIDByCode(memberArray);
				if (userBeans != null && userBeans.size() > 0) {
					members = new long[userBeans.size()];

					for (int i = 0, size = userBeans.size(); i < size; i++) {
						members[i] = userBeans.get(i).getId();
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return members;
	}
	
	

	public static String[] getMemberCodeArray() {
		return memberCodeArray;
	}

	public static boolean setMemberCodeArray(String codes) {

		try {
			String[] memberCodeArray = codes.split(",");

			FileOutputStream fos = new FileOutputStream(
					MyUtil.getRealPath(AllowMemberManager.class)
							+ "allowMember");

			for (int i = 0; i < memberCodeArray.length; i++) {
				fos.write(memberCodeArray[i].getBytes("utf-8"));
				fos.write("\n".getBytes("utf-8"));
			}
			fos.flush();
			fos.close();

			List<UserBean> userBeans = MemberDao
					.queryMemberIDByCode(memberCodeArray);
			if (userBeans != null && userBeans.size() > 0) {
				members = new long[userBeans.size()];
				for (int i = 0, size = userBeans.size(); i < size; i++) {
					members[i] = userBeans.get(i).getId();
				}
			}
			AllowMemberManager.memberCodeArray = memberCodeArray;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;

	}
}
